package base

import (
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/base"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/base/area"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/base/tenant"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
)

type SiteController struct {
	controller.BaseController
	areaService   area.AreaServiceIface
	tenantService tenant.TenantServiceIface
}

func NewSiteController(areaService area.AreaServiceIface, tenantService tenant.TenantServiceIface) *SiteController {
	return &SiteController{
		areaService:   areaService,
		tenantService: tenantService,
	}
}

// RegisterRouter
// 注册路由
func (c *SiteController) RegisterRouter(g *gin.RouterGroup) {
	// 网站基础信息
	g.GET("/tenant/info", c.tenantInfo)
	// 设置网站基本信息
	g.POST("/tenant/set_info", c.tenantSetInfo)
	// 获取区域配置信息
	g.GET("/area/trees", c.areaTrees)
	// 获取租户权益
	g.GET("/tenant/profit", c.tenantProfit)
}

func (c *SiteController) tenantInfo(ctx *gin.Context) {
	data, err := c.tenantService.GetTenantInfo(ctx)
	if err != nil {
		stark.Logger.Infof(ctx, "tenantInfo-err: %+v", err)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}
	c.Success(ctx, data)
}

func (c *SiteController) tenantSetInfo(ctx *gin.Context) {
	siteInfo := base.SiteInfo{}
	if err := ctx.ShouldBind(&siteInfo); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}

	if err := c.tenantService.TenantSetInfo(ctx, siteInfo.LogoFilePath, siteInfo.ProvinceCodeList); err != nil {
		stark.Logger.Infof(ctx, "tenantSetInfo-err: %+v", err)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}
	c.Success(ctx, nil)
}

func (c *SiteController) areaTrees(ctx *gin.Context) {
	areaTrees, err := c.areaService.AreaTrees(ctx)
	if err != nil {
		stark.Logger.Infof(ctx, "areaTrees-err: %+v", err)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}
	c.Success(ctx, map[string]interface{}{
		"list": areaTrees,
	})
}

func (c *SiteController) tenantProfit(ctx *gin.Context) {
	list, err := c.tenantService.Profit(ctx)
	if err != nil {
		stark.Logger.Infof(ctx, "tenantProfit-err: %+v", err)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}
	c.Success(ctx, map[string]interface{}{
		"list": list,
	})
}
